package com.zhida.jiyangcenter.mian

import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.resColor
import chooongg.base.utils.tipFail
import chooongg.base.utils.toast
import chooongg.base.widget.backlayout.ParallaxBackEnable
import chooongg.http.APIException
import com.flyco.animation.BounceEnter.BounceTopEnter
import com.flyco.animation.SlideExit.SlideBottomExit
import com.flyco.dialog.listener.OnBtnClickL
import com.flyco.dialog.widget.NormalDialog
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.mian.fragment.*
import com.google.android.material.tabs.TabLayout
import com.zhida.jiyangcenter.BuildConfig
import com.zhida.jiyangcenter.api.APIAccount
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.UpdataEntity
import com.zhida.jiyangcenter.utils.DownloadUtil
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_main1.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

@TitleBar(false, false)
@ParallaxBackEnable(false)
@ContentLayout(R.layout.activity_main1)
class MainActivity : BaseActivity() {
    private var checkedId = R.id.tab_main_home
    private val fragments = ArrayList<BaseFragment>().apply {
        add(MainHomeFragment())
//        add(MainArchivesFragment())
        add(MainStoreFragment())
        add(MainShopFragment())
        add(MainMeFragment().apply {
            setListener {
                this@MainActivity.main_top.setCurrentItem(it, true)
                this@MainActivity.navigation_group.check(R.id.tab_main_check_car)
            }
        })
    }
    private lateinit var adapter: Adapter

    private class Adapter(fm: FragmentManager, val fragments: ArrayList<BaseFragment>) :
        FragmentPagerAdapter(fm) {
        override fun getItem(position: Int) = fragments[position]
        override fun getCount() = fragments.size
        override fun getPageTitle(position: Int) = fragments[position].getTitle()
    }

    override fun initConfig(savedInstanceState: Bundle?) {
        super.initConfig(savedInstanceState)
        val window = activity.window
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        adapter = Adapter(
            supportFragmentManager,
            fragments
        )
        main_top.adapter = adapter
        main_top.offscreenPageLimit = fragments.size - 1
        navigation_group.setOnCheckedChangeListener { _, checkedId ->
            if (this.checkedId != checkedId) {
                this.checkedId = checkedId
                when (checkedId) {
                    R.id.tab_main_home -> main_top.setCurrentItem(0, false)
//                    R.id.tab_main_check_car -> main_top.setCurrentItem(1, false)
                    R.id.tab_main_order -> main_top.setCurrentItem(1, false)
                    R.id.tab_main_shangcheng -> main_top.setCurrentItem(2, false)
                    R.id.tab_main_me -> main_top.setCurrentItem(3, false)
                }
            }
        }
        //更新app
        getUpdateVersion()
    }

    private fun getUpdateVersion() {
        lifecycleScope.request({ APIAccount.service().update() }, object : BaseAPI<UpdataEntity>() {
            override fun onSuccess(t: UpdataEntity?, state: Int, msg: String) {
                if (t?.code ?: 0 > BuildConfig.VERSION_CODE) {
                    val dialog = NormalDialog(context)
                    dialog.content(t?.update_explain)
                        .style(NormalDialog.STYLE_TWO)//
                        .title("中昊云景："+t?.version)
                        .btnNum(1)
                        .btnTextColor(resColor(R.color.colorAccent))
                        .btnText("立即更新")
                        .titleTextSize(23f)
                        .showAnim(BounceTopEnter())
                        .dismissAnim(SlideBottomExit())
                        .show()
                    dialog.setCanceledOnTouchOutside(false)
                    dialog.setCancelable(false)
                    dialog.setOnBtnClickL(OnBtnClickL {
                        dialog.dismiss()
                        lifecycleScope.launch(Dispatchers.IO) {
                            DownloadUtil.get().download(t?.apk_path!!,
                                context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!.absolutePath,
                                "jiyang.apk",
                                object : DownloadUtil.OnDownloadListener {
                                    override fun onDownloadSuccess(file: File) {
                                        hideTipLoading()
                                        lifecycleScope.launch(
                                            Dispatchers.Main
                                        ) {
                                            installAPK(file, this@MainActivity)
                                        }
                                    }

                                    override fun onDownloading(progress: Int) {
                                        showTipLoading("下载中,请稍等...$progress%")
                                    }

                                    override fun onDownloadFailed(e: Exception) {
                                        hideTipLoading()
                                        toast(e.message ?: "下载失败")
                                    }
                                })
                        }
                    })
                }
            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }

        })


    }

    fun installAPK(file: File, mAct: Activity) {
        val authority = "com.vehicle.inspection.FileProvider"
        mAct.startActivity(getInstallAppIntent(file, authority, true))
    }

    private fun getInstallAppIntent(
        file: File?,
        authority: String,
        isNewTask: Boolean
    ): Intent? {
        if (file == null) return null
        val intent = Intent(Intent.ACTION_VIEW)
        val data: Uri
        val type = "application/vnd.android.package-archive"
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            data = Uri.fromFile(file)
        } else {
            intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            data = FileProvider.getUriForFile(this@MainActivity, authority, file)
        }
        intent.setDataAndType(data, type)
        return getIntent(intent, isNewTask)
    }

    private fun getIntent(intent: Intent, isNewTask: Boolean): Intent {
        return if (isNewTask) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) else intent
    }
}